import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import Signup from './views/Signup.vue'
import ColumnDetail from './components/ColumnDetail.vue'
import CreatePost from './views/CreatePost.vue'
import PostDetail from './views/PostDetail.vue'
import store from './store'
import axios from 'axios'
const routerHistory = createWebHistory()
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta:{ redirectAlreadyLogin:true }
    },
    {
      path: '/signup',
      name: 'signup',
      component: Signup,
      meta: { redirectAlreadyLogin: true }
    },
    {
      path: '/create',
      name: 'create',
      component: CreatePost,
      meta:{ requiredLogin:true }
    },
    {
      path: '/column/:id',
      name: 'column',
      component: ColumnDetail
    },
    {
      path: '/posts/:id',
      name: 'post',
      component: PostDetail
    }
  ]
})
//路由守卫 - 前置守卫
router.beforeEach((to,from,next)=>{
   /* console.log(to.meta)
   // 获取的路由有requiredLogin 同事没有isLogin 为false
    if (to.meta.requiredLogin && !store.state.user.isLogin){
     next({name:'login'}) //重定向到login页面
    } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin){
      next('/')
    } else {
     next()//继续下去
   } */
      const { user, token } = store.state;
      const { requiredLogin, redirectAlreadyLogin } = to.meta;
      if (!user.isLogin) {
        if (token) {
          axios.defaults.headers.common.Authorization = `Bearer ${token}`
          store.dispatch('fetchCurrentUser').then(() => {
            if (redirectAlreadyLogin) {
              next('/')
            } else {
              next()
            }
          }).catch(e => {
            console.error(e)
            localStorage.removeItem('token')
            next('login')
          })
        } else {
          if (requiredLogin) {
            next('login')
          } else {
            next()
          }
        }
      } else {
        if (redirectAlreadyLogin) {
          next('/')
        } else {
          next()
        }
      }
})

export default router